
import unittest
import helper.person as person

class TestSort(unittest.TestCase):

    class Student(object):
        def __init__(self,number,name):
            self.__no = number
            self.__name = name
            
        def get_number(self):
            return self.__no
        
        def get_name(self):
            return self.__name
        
    def setUp(self):
        self.__stud1 = TestSort.Student(1,"cheka")
        self.__stud2 = TestSort.Student(2,"stasi")
        self.__stud3 = TestSort.Student(3,"mss")
        
        self.__unsorted = [self.__stud3,self.__stud2,self.__stud1] 
        self.__number_sorted = [self.__stud1,self.__stud2,self.__stud3]
        self.__name_sorted = [self.__stud1,self.__stud3,self.__stud2]
    
    def test_sort_by_key(self):
        sorted_by_no = sorted(self.__unsorted,key=TestSort.Student.get_number)
        self.assertEqual(self.__number_sorted,sorted_by_no)
        
        sorted_by_name = sorted(self.__unsorted,key=TestSort.Student.get_name)
        self.assertEqual(self.__name_sorted,sorted_by_name)
        
    def test_sort_by_key2(self):
        alist = [person.Person(x,"p%d"%x) for x in xrange(4,0,-1)]
        ascending_list = [person.Person(x,"p%d"%x) for x in xrange(1,5)] 
        
        self.assertNotEqual(ascending_list,alist)
        
        alist.sort(key = lambda x : x._ssn)
        self.assertEqual(ascending_list,alist)
        
    def test_sort_by_cmpfunc(self):
        sorted_by_no = sorted(self.__unsorted,cmp = lambda x,y: x.get_number() - y.get_number())
        self.assertEqual(self.__number_sorted,sorted_by_no)
        
        sorted_by_name = sorted(self.__unsorted,cmp = lambda x,y: cmp(y.get_name(),x.get_name()))
        self.__name_sorted.reverse() # reverse in place
        self.assertEqual(self.__name_sorted,sorted_by_name)

if __name__ == "__main__":
    unittest.main()